package io.gitee.kotle.player.ui.view.exo

import android.content.Context
import android.util.AttributeSet
import androidx.media3.common.MediaItem
import io.gitee.kotle.player.core.IPlayer
import io.gitee.kotle.player.core.impl.exoplayer.IExoPlayerMode
import io.gitee.kotle.player.core.retry
import io.gitee.kotle.player.ui.ignoreError

class ExoPlayerPlayPauseView : PlayPauseView, IExoPlayerView {
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    override fun onPlayerViewConfigCreated(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigCreated(player, config)
        this.setOnClickListener {
            ignoreError {
                when (player.currentModelState) {
                    IPlayer.ModelState.Error,
                    IPlayer.ModelState.Stop,
                    IPlayer.ModelState.End -> {
                        player.retry()
                    }

                    IPlayer.ModelState.Pause -> {
                        player.play()
                    }

                    IPlayer.ModelState.Prepare,
                    IPlayer.ModelState.Buffer,
                    IPlayer.ModelState.Play -> {
                        player.pause()
                    }
                }
            }
            //view延时消失
            config.singleTapConfirmed.value = true
        }
    }


    override fun onPlayerViewConfigDestroyed(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigDestroyed(player, config)
        this.setOnClickListener(null)
    }

    override fun needPlayerListener(): Boolean {
        return true
    }

    override fun onModelState(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        state: IPlayer.ModelState
    ) {
        super.onModelState(player, state)
        when (state) {
            IPlayer.ModelState.Pause,
            IPlayer.ModelState.Error,
            IPlayer.ModelState.Stop,
            IPlayer.ModelState.End -> pause()

            IPlayer.ModelState.Prepare,
            IPlayer.ModelState.Buffer,
            IPlayer.ModelState.Play -> play()
        }
    }
}